package com.zhengb.algorithmdemo.exam.linear;

import java.math.BigDecimal;
import java.math.MathContext;

public class NumberUtil {

    //默认精度
    private static final int DEF_SCALE = 2;

    private static final MathContext DEFAULT_MATH_CONTEXT = MathContext.UNLIMITED;

    /**
     * 加法运算
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double add(double v1, double v2) {

        BigDecimal b1 = new BigDecimal(String.valueOf(v1));
        BigDecimal b2 = new BigDecimal(String.valueOf(v2));
        return b1.add(b2, DEFAULT_MATH_CONTEXT).doubleValue();

    }

    /**
     * 减法运算
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double sub(double v1, double v2) {

        BigDecimal b1 = new BigDecimal(String.valueOf(v1));
        BigDecimal b2 = new BigDecimal(String.valueOf(v2));
        return b1.subtract(b2, DEFAULT_MATH_CONTEXT).doubleValue();

    }

    /**
     * 乘法运算
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double mul(double v1, double v2) {

        BigDecimal b1 = new BigDecimal(String.valueOf(v1));
        BigDecimal b2 = new BigDecimal(String.valueOf(v2));
        return b1.multiply(b2, DEFAULT_MATH_CONTEXT).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();

    }

    /**
     * 除法运算
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double div(double v1, double v2) {

        BigDecimal b1 = new BigDecimal(String.valueOf(v1));
        BigDecimal b2 = new BigDecimal(String.valueOf(v2));
        return b1.divide(b2, DEF_SCALE, BigDecimal.ROUND_DOWN).doubleValue();

    }

    public static double divWithScale(double v1, double v2, int scale) {

        BigDecimal b1 = new BigDecimal(String.valueOf(v1));
        BigDecimal b2 = new BigDecimal(String.valueOf(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_DOWN).doubleValue();


    }

    /**
     * 类型转换,四舍五入
     *
     * @param v
     * @return
     */
    public static int intValue(double v) {

        return Long.valueOf(Math.round(v)).intValue();

    }


}
